package com.gxa.community.agent.config;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.core.JmsMessagingTemplate;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;

@Configuration
public class ActiveMQConfig {
    @Value("${spring.activemq.broker-url}")
    private String brokerUrl;
    @Value("${spring.activemq.user}")
    private String username;
    @Value("${spring.activemq.password}")
    private String password;
    @Value("${spring.activemq.queue-name}")
    private String queueName;
    @Value("${spring.activemq.topic-name}")
    private String topicName;

    @Bean(name = "queue")
    public Queue queue() {
        return new ActiveMQQueue(queueName);
    }

    @Bean(name = "topic")
    public Topic topic() {
        return new ActiveMQTopic(topicName);
    }

    @Bean
    public ConnectionFactory connectionFactory() {
//        return new ActiveMQConnectionFactory(username, password,
//                brokerUrl);
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(username,password,brokerUrl);
        connectionFactory.setTrustAllPackages(true);//这就是和配置文件起到一样作用
        return  connectionFactory;
    }

//    @Bean("jmsTemplate")
    @Bean
    public JmsMessagingTemplate jmsMessageTemplate() {
        return new JmsMessagingTemplate(connectionFactory());
    }

    @Bean
    public SimpleJmsListenerContainerFactory containerFactory(ConnectionFactory connectionFactory){
        SimpleJmsListenerContainerFactory containerFactory = new SimpleJmsListenerContainerFactory();
        containerFactory.setSessionTransacted(false);
        containerFactory.setSessionAcknowledgeMode(4);
        containerFactory.setConnectionFactory(connectionFactory);
        return containerFactory;
    }
}
